﻿/*
 * Toast8
 * All rights reserved
 * Copyright (C) 2014 Peter Nylander
 */

using System;
using System.Management;
using System.Runtime.InteropServices;

namespace Toast8.Common
{
    public class Win32Helper
    {
        [DllImport("user32.dll", SetLastError = true)]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
        public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll")]
        public static extern IntPtr SetFocus(IntPtr hWnd);

        [DllImport("user32.dll")]
        public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        [DllImport("user32.dll")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        internal const uint WM_APPCOMMAND = 0x0319;

        /// <summary>
        /// Send APP_COMMAND to window
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="cmd"></param>
        public static void SendAppCommand(IntPtr hWnd, APPCOMMAND cmd)
        {
            Win32Helper.SendMessage(hWnd, WM_APPCOMMAND, IntPtr.Zero, new IntPtr((long) cmd << 0x10));
        }

        /// <summary>
        /// Finds a windows specified by class name
        /// </summary>
        /// <param name="className"></param>
        /// <returns>true if window is available</returns>
        public static bool IsWindowAvailable(string className)
        {
            return Win32Helper.FindWindow(className, null) != IntPtr.Zero;
        }

        /// <summary>
        /// Finds a window specified by the class name and window title and set focuses on that window
        /// </summary>
        /// <param name="className"></param>
        /// <param name="windowName"></param>
        /// <returns></returns>
        public static IntPtr FindWindowAndFocus(string className, string windowName)
        {
            IntPtr hWindow = Win32Helper.FindWindow(className, windowName);
            Win32Helper.SetForegroundWindow(hWindow);
            return hWindow;
        }

        public void MonitorProcess()
        {

        }
    }

    public enum APPCOMMAND
    {
        APPCOMMAND_VOLUME_MUTE = 8,
        APPCOMMAND_VOLUME_DOWN = 9,
        APPCOMMAND_VOLUME_UP = 10,
        APPCOMMAND_MEDIA_NEXTTRACK = 11,
        APPCOMMAND_MEDIA_PREVIOUSTRACK = 12,
        APPCOMMAND_MEDIA_STOP = 13,
        APPCOMMAND_MEDIA_PLAY_PAUSE = 14,
        APPCOMMAND_MEDIA_PAUSE = 47,
        APPCOMMAND_MEDIA_FAST_FORWARD = 49,
        APPCOMMAND_MEDIA_REWIND = 50
    }

}
